package com.ryan.route.controller.front;

import com.ryan.route.entity.TravelRoute;
import com.ryan.route.entity.frontvo.RouteDetailVo;
import com.ryan.route.entity.frontvo.SearchRouteVo;
import com.ryan.route.feignclient.OrderClient;
import com.ryan.route.service.TravelRouteService;
import com.ryan.utils.JwtUtil;
import com.ryan.utils.R;
import com.ryan.utils.vo.OrderRoute;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/route/front")
public class FrontRouteController {

    @Autowired
    private OrderClient orderClient;

    @Autowired
    private TravelRouteService routeService;

    /**
     * 前台页面分页+条件查询
     * @param pageIndex
     * @param pageSize
     * @param searchRouteVo
     * @return
     */
    @PostMapping("/SearchRouteByVo/{pageIndex}/{pageSize}")
    public R SearchRouteByVo(@PathVariable long pageIndex,
                             @PathVariable long pageSize,
                             @RequestBody(required = false) SearchRouteVo searchRouteVo){
        Map<String, Object> map = routeService.SearchRouteByVo(pageIndex, pageSize, searchRouteVo);
        return R.ok().data(map);
    }

    /**
     * 根据路线id和会员id判断用户是否已经购买
     * @param routeId
     * @param request
     * @return
     */
    @GetMapping("/getRouteDetailById/{routeId}")
    public R getRouteDetailById(@PathVariable String routeId, HttpServletRequest request){
        RouteDetailVo routeDetailVo = routeService.getRouteDetailById(routeId);
        //判断是否已经购买
        boolean isBuy = false;
        String memberId = JwtUtil.getMemberIdByJwtToken(request);
        //前提是已经登陆
        if(!StringUtils.isEmpty(memberId)){
            isBuy = orderClient.isBuyRoute(routeId,memberId);
        }
        return R.ok().data("routeDetail", routeDetailVo).data("isBuy", isBuy);
    }

    /**
     * 根据id获取route,前台下单时获取，被order服务调用
     * @param id
     * @return
     */
    @GetMapping("/getRouteById/{id}")
    public OrderRoute getRouteById(@PathVariable String id){
        RouteDetailVo routeDetailVo = routeService.getRouteDetailById(id);
        OrderRoute orderRoute = new OrderRoute();
        BeanUtils.copyProperties(routeDetailVo,orderRoute);
        return orderRoute;
    }

    /**
     * 支付成功后更新路线销量，被order服务调用
     * @param orderRoute
     */
    @PostMapping("/updateBuyCount")
    public void updateBuyCount(@RequestBody OrderRoute orderRoute){
        routeService.updateBuyCount(orderRoute);
    }

}
